package cn.fl.grpcfg.controller;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.logger.eum.LogExceptionEnum;
import cn.cmm.base.framework.logger.eum.LogOperEnum;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.grpcfg.service.ISplGroupCfgDtlService;
import cn.fl.grpcfg.transform.SplGroupCfgDtlVOTransform;
import cn.fl.grpcfg.vo.SplGroupCfgDtlVO;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import fl.constant.facade.framework.constant.BusinessIdConstant;
import fl.spl.facade.framework.constant.SplSystemConstant;
import fl.spl.facade.grpcfg.condition.SplGroupCfgDtlQC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 集团管理划分配置表 控制层
 */
@Controller
@RequestMapping("/grpcfg/splgroupcfgdtl")
public class SplGroupCfgDtlController extends BaseController {

	/**
	 * SplGroupCfgDtl 服务层BEAN
	 */
	@Autowired
	private ISplGroupCfgDtlService splGroupCfgDtlService;

	@Autowired
	private ISysDictionaryApiService sysDictionaryApiService ;

	/**
	 * 到列表页面
	 */
	@RequestMapping(value = "/toFstPage.do", method = { RequestMethod.GET})
	public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {

		ModelAndView view = new ModelAndView("grpcfg/splGroupCfgDtl/splGroupDtlPage");
		
		return view;
	}
	
	/**
	 * 到新增修改页面
	 */
	@RequestMapping(value = "/toAddPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toAddPage(HttpServletRequest request, HttpServletResponse response) {

		ModelAndView view = new ModelAndView("grpcfg/splGroupCfgDtl/splGroupCfgDtlAdd");
		
		return view;
	}

	/**
	 * 到修改页面
	 */
	@RequestMapping(value = "/toModifyPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toModifyPage(HttpServletRequest request, HttpServletResponse response) {

		String id = request.getParameter("id");
		ModelAndView view = new ModelAndView("grpcfg/splGroupCfgDtl/splGroupCfgDtlModify");

		SplGroupCfgDtlQC splGroupCfgDtlQC = new SplGroupCfgDtlQC();
		splGroupCfgDtlQC.setIsNew(BaseConstant.IS_YESNO_YES);
		splGroupCfgDtlQC.setIsDel(BaseConstant.IS_YESNO_NO);
		List<SplGroupCfgDtlVO> splGroupCfgDtlVOS = this.splGroupCfgDtlService.searchList(splGroupCfgDtlQC);
		if(CollectionUtils.isNotEmpty(splGroupCfgDtlVOS)){
			view.addObject("splGroupCfgDtl",splGroupCfgDtlVOS.get(0));
		}else{
			view.addObject("splGroupCfgDtl",new SplGroupCfgDtlVO());
		}
		List<KeyValueVO> keyValueVOS = this.sysDictionaryApiService.getKvListWithAttr1("SPL0004","SPL_GRP_CFG","11000","0000");
		JSONArray jsonArray = new JSONArray();
		for(KeyValueVO keyValueVO : keyValueVOS){
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("text",keyValueVO.getKey());
			jsonObject.put("name",keyValueVO.getValue());

			jsonArray.add(jsonObject);
		}
		view.addObject("id", id);
		view.addObject("keyValueVOS", jsonArray);
		BaseLogUtils.newWebLogger("到修改页面").setLogOperType(LogOperEnum.REQ)
				.setSysCd(CurrentThreadContext.getCurrentSysCd())
				.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
				.setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
				.setWarning(false)
				.info();
		return view;
	}
	
	/**
	 * 到详情页面
	 */
	@RequestMapping(value = "/toDetailPage.do", method = { RequestMethod.GET})
	public ModelAndView toDetailPage(HttpServletRequest request, HttpServletResponse response) {

		String id = request.getParameter("id");
		ModelAndView view = new ModelAndView("grpcfg/splGroupCfgDtl/splGroupCfgDtlDetail");
		view.addObject("id", id);
		
		return view;
	}

	/**
	 * 初始化列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initList(HttpServletRequest request, HttpServletResponse response) {

		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		String searchName = request.getParameter("demo.name");
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}

		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}

		SplGroupCfgDtlQC qc = new SplGroupCfgDtlQC();
		if (StringUtils.isNotEmpty(searchName)) {
			//TODO SOMTHING
		}
		page.setCondition(qc);

		//TODO SOMETHING
		Pager pager = new Pager();//this.splGroupCfgDtlService.searchListPage(page);
		List<SplGroupCfgDtlVO> list = (List<SplGroupCfgDtlVO>) pager.getResultList();
		ListPageVO<SplGroupCfgDtlVO> listPage = new ListPageVO<SplGroupCfgDtlVO>(list, pager.getTotalCount());
		return listPage;
	}
	
	/**
	 * 新增
	 */
	@RequestMapping(value = "/add.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object add(HttpServletRequest request, HttpServletResponse response) throws BaseException {

		String name = request.getParameter("holdRatio");
		String roleTypCds  =request.getParameter("roleTypCds");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "新增成功!");
		SplGroupCfgDtlVO entity = new SplGroupCfgDtlVO();
		try {
			this.toComboAddDataByParameter(request,entity);
			//TODO ADD PARAM
			SplGroupCfgDtlQC qc = new SplGroupCfgDtlQC();
			qc.setIsDel(BaseConstant.IS_YESNO_NO);
			qc.setIsNew(BaseConstant.IS_YESNO_YES);
			Map<String,Object> mdfMap = new HashMap<>(4);
			mdfMap.put("isNew",BaseConstant.IS_YESNO_NO);
			mdfMap.put("mdfTm",new Date());
			mdfMap.put("mdfUsrId",CurrentThreadContext.getCurrentUserId());
			this.splGroupCfgDtlService.mdfAndAddSplGrpCfgDtl(qc,SplGroupCfgDtlVOTransform.toDTO(entity),mdfMap);
			BaseLogUtils.newWebLogger("新增数据DATA").setLogOperType(LogOperEnum.RESP)
					.setSysCd(CurrentThreadContext.getCurrentSysCd())
					.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
					.setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
					.setWarning(false)
					.setKeys("result", JSON.toJSONString(result))
					.info();
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.newWebLogger("新增对象失败,业务异常").setLogOperType(LogOperEnum.REQ)
					.setSysCd(CurrentThreadContext.getCurrentSysCd())
					.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
					.setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
					.setWarning(false)
					.setThrowable(ex)
					.warn(LogExceptionEnum.COMMON_CODE_0001);
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("系统错误,请联系管理员!");
			BaseLogUtils.newWebLogger("新增对象失败,系统异常").setLogOperType(LogOperEnum.REQ)
					.setSysCd(CurrentThreadContext.getCurrentSysCd())
					.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
					.setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
					.setWarning(false)
					.setThrowable(ex)
					.error(LogExceptionEnum.COMMON_CODE_0099);
		}
		return result;
	}

	/**
	 * 修改
	 */
	@RequestMapping(value = "/modify.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object modify(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		String name = request.getParameter("name");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "修改成功!");
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("数据不存在!");
			return result;
		}
		SplGroupCfgDtlVO entity = null;
		try {
			entity = new SplGroupCfgDtlVO();
			entity.setId(Long.valueOf(id));
			//entity.setName(name);
			//TODO ADD PARAM
			boolean success = this.splGroupCfgDtlService.modify(entity);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo("修改失败!");
			}
		} catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("系统错误,请联系管理员!");
		}
		
		return result;
	}

	/**
	 * 删除数据
	 */
	@RequestMapping(value = "/removeById.do", method = {RequestMethod.POST })
	@ResponseBody
	public DataResultVO removeById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "删除成功!");
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("主键不能为空!");
			return result;
		}
		try {
			this.splGroupCfgDtlService.removeById(Long.valueOf(id));
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
		} catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("系统错误,请联系管理员!");
		}
		return result;
	}

	/**
	 * 得到一条记录
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getById.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getById(HttpServletRequest request, HttpServletResponse response) throws BaseException {

		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "操作成功!");
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("主键不能为空!");
			return result;
		}
		
		try {
			SplGroupCfgDtlVO vo = this.splGroupCfgDtlService.selectById(Long.valueOf(id));
			if(null == vo){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo("数据不存在!");
			}
			result.setData(vo);
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
		} catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("系统错误,请联系管理员!");
		}
		
		return result;
	}


	private void toComboAddDataByParameter(HttpServletRequest request, SplGroupCfgDtlVO vo){
		if(vo == null ){
			vo = new SplGroupCfgDtlVO();
		}
		String holdRatio = request.getParameter("holdRatio");
		String roleTypCds  =request.getParameter("roleTypCd");
		if(StringUtils.isEmpty(holdRatio)){
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_500,BaseExceptionConstant.BASE_EXCEPTION_CODE_500_NAME);
		}
		if(StringUtils.isEmpty(roleTypCds)){
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_500,BaseExceptionConstant.BASE_EXCEPTION_CODE_500_NAME);
		}else{
			JSONArray jsonArray = JSONArray.parseArray(roleTypCds);
			StringBuffer roleTypCdSb = new StringBuffer() ;
			for(int i= 0 ; i< jsonArray.size() ; i++){
				roleTypCdSb.append(String.valueOf(jsonArray.get(i)));
				if(i != (jsonArray.size() - 1)){
					roleTypCdSb.append(",");
				}
			}
			vo.setRoleTypCd(roleTypCdSb.toString());
		}
		vo.setHoldRatio(Double.valueOf(holdRatio));
		vo.setIsNew(BaseConstant.IS_YESNO_YES);
		vo.setIsDel(BaseConstant.IS_YESNO_NO);
		vo.setCrtTm(new Date());
		vo.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
	}
}

